import React, { Component } from 'react';
import { user_login} from '../utils/api'
import {request_collectlist_action,request_shopcartlist_action} from '../store/ActionCreator'
import {connect} from 'react-redux'

class MyLogin extends Component {
    constructor(props) {
        super(props)
        this.state = {
            phone: "",
            pass: ""
        }
    }
    login() {
        if (this.state.phone && this.state.pass) {
            user_login(this.state).then((res) => {
                if(res.data.code==200){
                    alert("登陆成功！")
                    localStorage.setItem("token",res.data.token)
                    localStorage.setItem("userinfo",JSON.stringify(res.data.userinfo))
                    this.props.history.push('/')
                    // 
                    this.props.collectlist()
                    this.props.shopcartlist()
                    // var userinfo=localStorage.getItem('userinfo')
                    // good_favlist({userid:userinfo.id}).then((res)=>{
                    //     localStorage.setItem('collectlist',JSON.stringify(res.data.list))
                    // })
                    // shopcart_list({userid:userinfo.id}).then((res)=>{
                    //     localStorage.setItem('shopcartlist',JSON.stringify(res.data.list))
                    // })
                }
            })
        } else {
            alert("请输入完整信息！")
        }
    }
    handleChange(e) {
        this.setState({
            [e.currentTarget.name]: e.currentTarget.value
        })
    }
    render() {
        return (
            <div className='mylogin'>
                <div className='title'>用户登录</div>
                <div className="login">
                    <div className="line">
                        <input type="text" placeholder='请输入账号' name='phone' defaultValue={this.state.phone} onChange={(e) => { this.handleChange(e) }} />
                    </div>
                    <div className="line">
                        <input type="password" placeholder='请输入密码' name='pass' defaultValue={this.state.pass} onChange={(e) => { this.handleChange(e) }} />
                    </div>
                    <div className="line">
                        <button onClick={() => { this.login() }}>登录</button>
                    </div>
                    <div className="line">
                        <a href="/register">注册</a>
                    </div>
                </div>
            </div>
        );
    }
}

export default connect(
    (state)=>{
        return{}
    },
    (dispatch)=>{
        return {
            collectlist(){
                dispatch(request_collectlist_action())
            },
            shopcartlist(){
                dispatch(request_shopcartlist_action())
            }
        }
    }
)(MyLogin);